package at.playbox.server.businesslogic;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.Formatter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.MessageContext;

import sun.misc.BASE64Decoder;
import at.playbox.server.entity.User;

public class AuthenticationService
{
	String username = null;

	public boolean isAuthenticated(MessageContext mc) throws IOException
	{
		HttpServletRequest request = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
		return isAuthenticated(request);
	}

	public boolean isAuthenticated(HttpServletRequest request) throws IOException
	{
		String password = null;
		User user = new User();
		UserService userService = new UserService();

		String authhead = request.getHeader("Authorization");
		if (authhead != null)
		{
			// *****Decode the authorisation String*****
			// String usernpass = Base64.decode(authhead.substring(6));
			String usernpass = new String(new BASE64Decoder().decodeBuffer(authhead.substring(6)), "UTF-8");
			// *****Split the username from the password*****
			username = usernpass.substring(0, usernpass.indexOf(":"));
			System.out.println("AuthenticationService " + this.username);
			password = usernpass.substring(usernpass.indexOf(":") + 1);
			if (userService.getUserByUsername(username) != null)
			{
				user = userService.getUserByUsername(username);
				if (checkCredentials(username, password, user))
				{
					return true;
				}
			}
		}
		return false;
	}

	public void sendAuthenticationResponse(MessageContext mc) throws IOException
	{
		HttpServletResponse response = (HttpServletResponse) mc.get(MessageContext.SERVLET_RESPONSE);
		sendAuthenticationResponse(response);
	}

	public void sendAuthenticationResponse(HttpServletResponse response) throws IOException
	{
		response.setHeader("WWW-Authenticate", "Basic realm=\"Authorisation PlayBox\"");
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "");
		PrintWriter out = response.getWriter();
		out.println("Access denied!");
		out.close();
	}

	public String getUsername()
	{
		return this.username;
	}

	public boolean checkCredentials(String username, String password, User user)
	{
		password = calculateHash(user.getSalt(), password);
		System.out.println(password);
		if (username.equals(user.getUsername()) && password.equals(user.getHash()))
		{
			System.out.println("true checkCredentials");
			return true;
		}
		System.out.println("Fehler! wrong credentials");
		return false;
	}

	private String calculateHash(String salt, String passwd)
	{
		try
		{
			String msg = salt + passwd;
			System.out.println(msg);
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] encryptMsg = md.digest(msg.getBytes());

			// return new String(encryptMsg);

			Formatter formatter = new Formatter();

			for (byte b : encryptMsg)
			{
				formatter.format("%02x", b);
			}
			System.out.println(formatter.toString());
			return formatter.toString();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}
}